package com.norrielm.GooglePlusPosts.models;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.norrielm.GooglePlusPosts.GooglePlusPresenter;
import com.norrielm.GooglePlusPosts.R;

/**
 * Loads {@link Post} data into the list view.
 * 
 * @author Lauren Norrie (norrielm)
 */
public class PostAdapter extends BaseAdapter implements GooglePlusPresenter.Adapter {

	private ArrayList<Post> posts;
	private LayoutInflater mInflater;

	public PostAdapter(Context context, ArrayList<Post> results) {
		posts = results;
		mInflater = LayoutInflater.from(context);
	}
	
	public PostAdapter(Context context) {
		this(context, new ArrayList<Post>());
	}
	
	public void setPosts(ArrayList<Post> results) {
		this.posts = results;
		if (posts.isEmpty()) {
			posts.add(new Post("","Nothing to show!"));
		}
		notifyDataSetChanged();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.post, null);
			holder = new ViewHolder();
			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.text = (TextView) convertView.findViewById(R.id.text);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.name.setText(posts.get(position).getName());
		holder.text.setText(posts.get(position).getText());

		return convertView;
	}

	public int getCount() {
		return posts.size();
	}

	public Object getItem(int position) {
		return posts.get(position);
	}

	public long getItemId(int position) {
		return position;
	}
	
	private static class ViewHolder {
		TextView name;
		TextView text;
	}
}
